package com.weimob.xh.util;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import org.springframework.core.io.ClassPathResource;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QRCodeGenerator2 {
    public static void main(String[] args) {
        String outDir = "D:\\work\\2024\\temp\\item";
        String url = "https://www.baidu.com/?schoolId=123456&gradeCode=04"; // 要生成二维码的链接

        generateAndSaveQRCode(url, outDir);
    }

    public static void generateAndSaveQRCode(String url, String outDir) {
        Map<String, String> parameters = extractParameters(url);
        String schoolId = parameters.get("schoolId");
        String gradeCode = parameters.get("gradeCode");

        String templateImagePath = "template.png";
        String folderPath = outDir + File.separator + schoolId + File.separator + gradeCode;
        String filePathQr = folderPath + File.separator + "qrcode.png";
        String filePath = folderPath + File.separator + "qrcodeAndTmp.png";

        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        BufferedImage qrCodeImage = generateQRCode(url, filePathQr);

        // 将带有二维码的图片打包到指定文件夹中
        BufferedImage templateImage = readImage(templateImagePath);
        BufferedImage resultImage = overlayImages(templateImage, qrCodeImage, 330, 940); // 像素：假设二维码放在(320, 940)的位置
        writeImage(resultImage, filePath);

        String outputFolderPath = outDir + File.separator + schoolId + File.separator + gradeCode;
        saveImageWithQRCode(resultImage, outputFolderPath);
        System.out.println("带有二维码的图片已保存至：" + outputFolderPath);
    }

    public static BufferedImage generateQRCode(String text, String filePath) {
        int width = 500;
        int height = 500;
        String format = "png";

        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
            Path path = Paths.get(filePath);
            MatrixToImageWriter.writeToPath(bitMatrix, format, path);
            System.out.println("二维码已生成至：" + filePath);

            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    public static BufferedImage readImage(String imagePath) {
        try {
            // 获取图片资源文件
            ClassPathResource resource = new ClassPathResource(imagePath);
            return ImageIO.read(resource.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void writeImage(BufferedImage image, String outputPath) {
        try {
            File outputFile = new File(outputPath);
            ImageIO.write(image, "png", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static BufferedImage overlayImages(BufferedImage templateImage, BufferedImage overlayImage, int x, int y) {
        BufferedImage combinedImage = new BufferedImage(templateImage.getWidth(), templateImage.getHeight(), BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = combinedImage.createGraphics();
        g2d.drawImage(templateImage, 0, 0, null);
        g2d.drawImage(overlayImage, x, y, null);
        g2d.dispose();
        return combinedImage;
    }

    public static Map<String, String> extractParameters(String url) {
        Map<String, String> parameters = new HashMap<>();
        String patternString = "([^?=&]+)(=([^&]*))?";
        Pattern pattern = Pattern.compile(patternString);
        Matcher matcher = pattern.matcher(url.substring(url.indexOf("?") + 1));

        while (matcher.find()) {
            String key = matcher.group(1);
            String value = matcher.group(3);
            parameters.put(key, value);
        }

        return parameters;
    }

    public static void saveImageWithQRCode(BufferedImage image, String outputFolderPath) {
        try {
            File outputFolder = new File(outputFolderPath);
            if (!outputFolder.exists()) {
                outputFolder.mkdirs();
            }

            File outputFile = new File(outputFolderPath + File.separator + "image_with_qrcode.png");
            ImageIO.write(image, "png", outputFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}